﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="WaitSchedulerJobCmdlet.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace CloudBlitz.Powershell.Cmdlets
{
    using System;
    using System.Collections.Generic;
    using System.Management.Automation;

    using System.Threading;
    using HpcSchedulerManagement.DataContracts;

    [Cmdlet("Wait", "SchedulerJob")]
    public class WaitSchedulerJobCmdlet : HpcSchedulerCmdletBase
    {
        private readonly IList<HpcSchedulerManagement.DataContracts.JobState> terminalStates = new List<HpcSchedulerManagement.DataContracts.JobState>
        {
                HpcSchedulerManagement.DataContracts.JobState.Failed,
                HpcSchedulerManagement.DataContracts.JobState.Finished,
                HpcSchedulerManagement.DataContracts.JobState.Canceled
        };

        [Parameter(Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public int JobId { get; set; }

        [Parameter]
        [PSDefaultValue(Value = 10)]
        [ValidateRange(1, 100)]
        public int PauseSeconds { get; set; }

        [Parameter]
        public IList<HpcSchedulerManagement.DataContracts.JobState> TerminalStates { get; set; }

        protected override void ProcessRecord()
        {
            try
            {
                base.ProcessRecord();
                this.WaitJobProcess();
            }
            catch (Exception ex)
            {
                this.ThrowTerminatingError(this.HandleException(ex).Result);
            }
        }

        private void WaitJobProcess()
        {
            var client = this.CreateClient();

            SchedulerJob job;
            var terminalStates = this.TerminalStates ?? this.terminalStates;

            do
            {
                job = client.GetJob(this.Credentials.ClusterName, this.JobId, null).Result;
                Thread.Sleep(this.PauseSeconds);

                if (job != null)
                {
                    this.WriteVerbose(string.Format("Job is in {0} state", job.State.ToString()));
                }
            }
            while (job != null && !terminalStates.Contains(job.State));

            if (job != null)
            {
                this.WriteObject(job.State);
            }
        }
    }
}